import axios, {AxiosRequestConfig} from 'axios';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Session} from '/@/utils/storage';

interface Respone<T> {
    success: boolean,
    code: number,
    data: T,
    msg: string
}

// 配置新建一个 axios 实例
const service = axios.create({
    baseURL: import.meta.env.VITE_API_URL as any,
    timeout: 120000,
    headers: {'Content-Type': 'application/json'},
});

// 添加请求拦截器
service.interceptors.request.use(
    (config) => {
        let url: string | undefined = config.url;
        let tokenOjb = {
            api: Session.get('token'),
            chartBI: 'Bearer ' + Session.get('chartBIToken'),
        }
        if (url != undefined) {
            let requestPathType = url.match(/\/([^\/]+)\/([^\/]+)/);

            (<any>config.headers).common['Authorization'] = `${tokenOjb[requestPathType[1]]}`;
        }
        /*if (Session.get('token')) {
            (<any>config.headers).common['Authorization'] = `${Session.get('token')}`;
        }*/
        // 在发送请求之前做些什么 token
        return config;
    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 添加响应拦截器
service.interceptors.response.use(
    (response) => {
        // 对响应数据做点什么
        const res = response.data;
        if (res.code && res.code !== 200) {
            // `token` 过期或者账号已在别处登录
            if (res.code === 401 || res.code === 4001 || res.msg == "TOKEN失效") {

                ElMessageBox.alert('您已被登出，请重新登录', '提示', {})
                    .then(() => {
                    })
                    .catch(() => {
                    });
                setTimeout(() => {
                    Session.clear(); // 清除浏览器全部临时缓存
                    window.location.href = '/'; // 去登录页
                }, 2000);

            } else if (res.code == 500) {
                return response.data;
            }
            return Promise.reject(res);
        } else {
            return response.data;
        }
    },
    (error) => {
        // 对响应错误做点什么
        if (error.message.indexOf('timeout') != -1) {
            ElMessage.error('网络超时');
        } else if (error.message == 'Network Error') {
            ElMessage.error('网络连接错误');
        } else {
            if (error.response.data) ElMessage.error(error.response.statusText);
            else ElMessage.error('接口路径找不到');
        }
        return Promise.reject(error);
    }
);


export function get<T>(url: string, params?: object): Promise<T> {
    return service.get(url).then(res => res.data).catch(err => console.error(err));
}


export function post<T>(url: string, data?: object): Promise<T> {
    return service.post(url, data).then(res => res.data);
}


// 导出 axios 实例
export default service;
